<?php
namespace app\admin\controller;
use think\Db;
class Money extends Base{
    public function get(){
        if(request()->isAjax ()){
            extract (input ());
            $map = [];
            if(isset($role)&&$role != ""){
                $map['o_pay_type'] = $role;
            }
            $area = [];
            if(session ('area')){
                $area = "u.user_area IN ('".session('area')."') OR s.shop_qu_id IN ('".session('area')."')";
            }
            if(isset($key)&&$key!="")
            {
                $map['o_order_num|o_account'] = ['like',"%" . $key . "%"];
            }
            $map['o_type'] = 3;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('order o')
                ->join('u_user u','o.o_user_id = u.user_id','left')
                ->join('shop s','o.o_shop_id = s.shop_id','left')
                ->where($map)
                ->where($area)
                ->count();
            $lists = Db::name('order o')
                ->join('u_user u','o.o_user_id = u.user_id','left')
                ->join('shop s','o.o_shop_id = s.shop_id','left')
                ->where($map)
                ->where($area)
                ->page($Nowpage,$limits)
                ->order('o_add_time desc')
                ->select ();
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        if(session('area')){
            $whereForShop = "o.o_type = 3 AND o.o_tixian_status = 2 AND s.shop_qu_id IN(".session('area').")";
            $whereForMonth = "o.o_type = 3 AND o.o_tixian_status = 2 AND (u.user_area IN (".session('area').") OR s.shop_qu_id IN (".session('area')."))";
        }else{
            $whereForShop = "o.o_type = 3 AND o.o_tixian_status = 2 AND s.shop_qu_id is not null";
            $whereForMonth = "o.o_type = 3 AND o.o_tixian_status = 2";
        }
        $shop = Db::name('order o')
            ->join('shop s','o.o_shop_id = s.shop_id','left')
            ->where($whereForShop)
            ->sum('o_money');
        $month = Db::name('order o')
            ->join('shop s','o.o_shop_id = s.shop_id','left')
            ->join('u_user u','o.o_user_id = u.user_id','left')
            ->whereTime('o_add_time', 'last month')
            ->where($whereForMonth)
            ->sum('o_money');
        $today = Db::name('order o')
            ->join('shop s','o.o_shop_id = s.shop_id','left')
            ->join('u_user u','o.o_user_id = u.user_id','left')
            ->whereTime('o_add_time', 'today')
            ->where($whereForMonth)
            ->sum('o_money');
        $yesterday =  Db::name('order o')
            ->join('shop s','o.o_shop_id = s.shop_id','left')
            ->join('u_user u','o.o_user_id = u.user_id','left')
            ->whereTime('o_add_time', 'yesterday')
            ->where($whereForMonth)
            ->sum('o_money');
        return $this->fetch('money/get',['shop'=>$shop,'month'=>$month,'today'=>$today,'yesterday'=>$yesterday]);
    }


    public function tixian(){
        extract (input ());
        $order = Db::name('order')->where(['o_id'=>$o_id])->find();
        if (!empty($order['o_user_id'])) {
            $conf = Db::name('jifen_conf')->where(['conf_id'=>30])->value ('conf_rate');//手续费比例
        }else{
            $conf = Db::name('jifen_conf')->where(['conf_id'=>8])->value ('conf_rate');//手续费比例
        }
        $money = $order['o_money'] - ($order['o_money'] * $conf);//最终金额
        Db::startTrans ();
        try{
            if($type == 2){//通过
                if(!$order['o_user_id']){ //商户提现
                    $have_money = Db::name('shop')->where('shop_id',$order['o_shop_id'])->value ('shop_balance');
                    if($order['o_money'] > $have_money || $have_money <= 0 || !$have_money){
                        return json(['code'=>100,'msg'=>'提现金额大于可提现金额']);
                    }
                }
                if($order['o_pay_type'] == 1){//支付宝
                    $ali = new \app\api\controller\Ali();
                    $res =  $ali->tixianAgreeShopOrWork($order['o_order_num'],$money,$order['o_account'],$order['o_real_name']);
                    $msg = '支付宝';
                }else{//微信
//                    return json(['code'=>100,'msg'=>'暂未开通']);
                    if($order['o_openid'] == ''){
                        return json(['code'=>100,'msg'=>'提现失败，缺少openid']);
                    }
                    if($order['o_user_id']){
                        $wx = new \app\api\controller\Weixin();
                        $res = $wx->userTiXian($order['o_order_num'],$order['o_openid'],$money,$order['o_real_name']);
                    }else{
                        $wx = new \app\api\controller\Weixinshop();
                        $res = $wx->userTiXian($order['o_order_num'],$order['o_openid'],$money,$order['o_real_name']);
                    }
                    $msg = '微信';
                }
                if($res['status'] == 200){
                    if($order['o_user_id']){//用户提现
                        if (!empty($order['o_sort']) && $order['o_sort'] == 1) {
                            Db::name('u_user')->where('user_id',$order['o_user_id'])->dec ('user_money_balance',$order['o_money'])->inc ('user_money_balance_yet',$order['o_money'])->inc('user_tixian_money',$order['o_money'])->update (['user_tixian_time'=>date('Y-m-d'),'user_edit_time'=>date('Y-m-d H:i:s')]);
                        }else{
                            Db::name('u_user')->where('user_id',$order['o_user_id'])->dec ('user_balance',$order['o_money'])->inc ('user_balance_yet',$order['o_money'])->inc('user_tixian_money',$order['o_money'])->update (['user_tixian_time'=>date('Y-m-d'),'user_edit_time'=>date('Y-m-d H:i:s')]);
                        }

                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'余额提现','n_content'=>'您提现了'.$order['o_money'].'元'."，已提现至您的{$msg}账户，请注意查收！",'n_images'=>'','n_type'=>3,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try {
							$this->jpushUser(1,$order['o_user_id'],'您提现了'.$order['o_money'].'元'."，已提现至您的{$msg}账户，请注意查收！",json([]));//Todo
						} catch (\Exception $e) {}
						
                    }else{//商户提现
                        Db::name('shop')->where('shop_id',$order['o_shop_id'])->dec ('shop_balance',$order['o_money'])->inc('shop_tixian_money',$order['o_money'])->update (['shop_tixian_time'=>date('Y-m-d'),'shop_edit_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>2,'n_title'=>'余额提现','n_content'=>'您提现了'.$order['o_money'].'元'."，已提现至您的{$msg}账户，请注意查收！",'n_images'=>'','n_type'=>3,'n_user_id'=>$order['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try {
							$this->jpushShop(1,$order['o_shop_id'],'您提现了'.$money.'元'."，已提现至您的{$msg}账户，请注意查收！",json([]));//Todo
						} catch (\Exception $e) {}
						
                    }
                    Db::name('admin')->where('id',1)->setDec ('balance',$money);
                    Db::name('order')->where(['o_id'=>$o_id])->update (['o_third_order_num'=>$res['msg'],'o_pay_status'=>2]);
                }else{
                    return json(['code'=>100,'msg'=>$res['msg']]);
                }
            }else{
                if($order['o_user_id']){
                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'余额提现','n_content'=>'您的提现申请已被驳回','n_images'=>'','n_type'=>3,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                    try {
							$this->jpushUser(1,$order['o_user_id'],'您的提现申请已被驳回',json([]));//Todo
						} catch (\Exception $e) {}
					
                }else{
                    Db::name('notice')->insert (['n_to'=>2,'n_title'=>'余额提现','n_content'=>'您的提现申请已被驳回','n_images'=>'','n_type'=>3,'n_user_id'=>$order['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                    try {
							$this->jpushShop(1,$order['o_shop_id'],'您的提现申请已被驳回',json([]));//Todo
						} catch (\Exception $e) {}
					
                }
            }
            Db::name('order')->where(['o_id'=>$o_id])->setField('o_tixian_status',$type);
            Db::commit ();
            return json(['code'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['code'=>100,'msg'=>'操作失败']);
        }
    }


    public function cash(){
        if(request()->isAjax ()){
            extract (input ());
            $map = [];
            if(isset($role)&&$role != ""){
                $map['o_pay_type'] = $role;
            }
            $area = [];
            // if(session ('area')){
            //     $area = "u.user_area IN ('".session('area')."') OR s.shop_qu_id IN ('".session('area')."')";
            // }
            if(session ('area')){
                $area = "s.shop_qu_id IN ('".session('area')."')";
            }
            if(isset($key)&&$key!="")
            {
                $map['o_order_num'] = ['like',"%" . $key . "%"];
            }
            $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
            $shop_total = 0;
            if(isset($shopName) && $shopName != "")
            {
                $shopId = Db::name('shop')->where('shop_name', $shopName)->value('shop_id');
                $map['s.shop_id'] = ['=', $shopId];
                
                $total = Db::query("SELECT (
                    sum(case when o_type = 4 then o_money else 0 end)
                    - 
                    sum(case when o_type = 5 then o_money else 0 end)
                    - sum(case when o_type = 7 then o_jifen * ? else 0 end)
                ) as money FROM up_order
                WHERE `o_type` IN (4,5,7) AND `o_pay_status` = 2 and o_shop_id = ?", [$rat, $shopId]);
                if (!empty($total)) {
                    $shop_total = $total[0]['money'];
                }
            }
            $map['o_type'] = ['in','4,5,7'];
            $map['o_pay_status'] = 2;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('order o')
                ->join('shop s','o.o_shop_id = s.shop_id','left')
                ->where($map)
                ->where($area)
                ->count();
            $lists = Db::name('order o')
                ->join('shop s','o.o_shop_id = s.shop_id','left')
                ->where($map)
                ->where($area)
                ->page($Nowpage,$limits)
                ->order('o_add_time desc')
                ->select ();
            
            $this->parseData($lists, $rat);

            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists,'shop_total'=>$shop_total]);
        }else{
            $all = Db::name('shop')->sum('shop_pledge_money');
            $yesterday_in = Db::name('order')
                ->whereTime('o_add_time', 'yesterday')
                ->where(['o_type'=>4,'o_pay_status'=>2])
                ->sum('o_money');
            $yesterday_out = Db::name('order')
                ->whereTime('o_add_time', 'yesterday')
                ->where(['o_type'=>5,'o_pay_status'=>2])
                ->sum('o_money');
            $today =  Db::name('order')
                ->whereTime('o_add_time', 'today')
                ->where(['o_type'=>5,'o_pay_status'=>2])
                ->sum('o_money');
            return $this->fetch('money/cash',['all'=>$all,'yesterday_in'=>$yesterday_in,'yesterday_out'=>$yesterday_out,'today'=>$today]);
        }
    }

    // 格式数据
    function parseData(&$lists, $rat) {
        
        if(empty($lists)){
            return;
        }
        
        foreach ($lists as $k=>&$v) {
            $type = '';
            if ($v['o_type'] == 4) {
                $type = '交押金';
            } else if($v['o_type'] == 7){
                $v['o_money'] = $v['o_jifen'] * $rat;
                $type = '扣押金(送积分)';
            } else {
                if (null != $v['o_third_order_num']) {
                    $type = '退押金';
                } else {
                    $type = '扣押金';
                }
            }
            
            $v['type'] = $type;
            
            $payType = '';
            if ($v['o_pay_type'] == 1) {
                $payType = '支付宝';
            } else if ($v['o_pay_type'] == 2) {
                $payType = '微信';
            } else if ($v['o_pay_type'] == 3) {
                $payType = '余额';
            }
            
            $v['pay_type'] = $payType;

        }
    }

    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function excelAdmin(){
        extract(input());
        
        $map = [];
        if(isset($role)&&$role != ""){
            $map['o_pay_type'] = $role;
        }
        $area = [];
        if(session ('area')){
            $area = "s.shop_qu_id IN ('".session('area')."')";
        }
        if(isset($key)&&$key!="")
        {
            $map['o_order_num'] = ['like',"%" . $key . "%"];
        }

        if(isset($shopName) && $shopName != "")
        {
            $map['s.shop_name'] = ['like',"%" . $shopName . "%"];
        }
        $map['o_type'] = ['in','4,5,7'];
        $map['o_pay_status'] = 2;
        
        $lists = Db::name('order o')
            ->join('shop s','o.o_shop_id = s.shop_id','left')
            ->where($map)
            ->where($area)
            ->order('o_add_time desc')
            ->select ();
        $cellname = [
            ['o_id','ID',15,'LEFT'],
            ['type','类型',15,'LEFT'],
            ['shop_name','店铺',15,'LEFT'],
            ['o_order_num','订单号',20,'LEFT'],
            ['o_money','金额',15,'LEFT'],
            ['pay_type','第三方',15,'LEFT'],
            ['o_add_time','众筹时间',15,'LEFT']
        ];
        $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
        $this->parseData($lists, $rat);

        $res = exportExcel('押金记录', 'money', $cellname, $lists);
        return json($res);
    }

}